<template>
  <div class="min-h-screen bg-gradient-to-br from-purple-50 to-pink-50 p-6">
    <div class="max-w-6xl mx-auto">
      <header class="mb-6">
        <h1 class="text-3xl font-bold text-gray-900">紫微斗数排盘</h1>
        <p class="text-sm text-gray-600">输入出生信息，生成简易星盘，在线紫薇斗数，紫薇斗数AI解盘。</p>
      </header>

      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="bg-white shadow rounded-lg p-4">
          <div class="space-y-3">
            <div>
              <label class="block text-sm text-gray-700">姓名</label>
              <input v-model="name" class="mt-1 block w-full border rounded px-3 py-2" placeholder="姓名（可选）" />
            </div>

            <div>
              <label class="block text-sm text-gray-700">日期类型</label>
              <div class="mt-1 flex items-center space-x-4">
                <label class="inline-flex items-center">
                  <input type="radio" value="solar" v-model="dateType" class="mr-2" /> 阳历
                </label>
                <label class="inline-flex items-center">
                  <input type="radio" value="lunar" v-model="dateType" class="mr-2" /> 农历
                </label>
              </div>
            </div>

            <div>
              <label class="block text-sm text-gray-700">出生日期</label>
              <input type="date" v-model="date" class="mt-1 block w-full border rounded px-3 py-2" />
            </div>

            <div>
              <label class="block text-sm text-gray-700">时辰</label>
              <select v-model="timeIndex" class="mt-1 block w-full border rounded px-3 py-2">
                <option v-for="opt in timeOptions" :key="opt.value" :value="opt.value" v-text="opt.label"></option>
              </select>
            </div>

            <div class="flex items-center space-x-4">
              <div>
                <label class="block text-sm text-gray-700">性别</label>
                <div class="mt-1 flex items-center space-x-3">
                  <label class="inline-flex items-center"><input type="radio" value="male" v-model="gender" class="mr-2"/> 男</label>
                  <label class="inline-flex items-center"><input type="radio" value="female" v-model="gender" class="mr-2"/> 女</label>
                </div>
              </div>
              <div v-if="dateType === 'lunar'" class="flex items-center">
                <label class="inline-flex items-center"><input type="checkbox" v-model="isLeapMonth" class="mr-2" /> 闰月</label>
              </div>
            </div>

            <div>
              <button @click="onGenerate" :disabled="loading" class="w-full bg-purple-600 hover:bg-purple-700 text-white py-2 rounded">
                <span v-if="!loading">立即排盘</span>
                <span v-else>生成中...</span>
              </button>
            </div>

            <p class="text-xs text-gray-500">提示：算法来自于开源库iztro</p>
          </div>
        </div>

        <div class="lg:col-span-2">
          <div class="bg-white shadow rounded-lg p-4">
            <div v-if="!palaces.length && !loading" class="text-center py-10 text-gray-500">
              请填写出生信息并点击“立即排盘”以查看星盘。
            </div>

            <div v-if="loading" class="text-center py-10">
              <div class="inline-block w-12 h-12 border-4 border-purple-300 border-t-purple-600 rounded-full animate-spin"></div>
              <div class="mt-3 text-sm text-gray-600">正在生成星盘，请稍候...</div>
            </div>

            <div v-if="palaces.length" class="space-y-4">
              <div class="flex items-center justify-between">
                <div>
                  <div class="text-sm text-gray-500">五行局：<span class="font-medium text-gray-800">{{ fiveElementsClass }}</span></div>
                  <div class="text-sm text-gray-500">命宫主星：<span class="font-medium text-gray-800">{{ majorStar }}</span></div>
                </div>
                <div class="flex items-center space-x-3">
                  <button @click="sendOverview('财运')" class="px-3 py-1 bg-yellow-400 rounded text-sm">财</button>
                  <button @click="sendOverview('事业')" class="px-3 py-1 bg-blue-400 rounded text-sm">业</button>
                  <button @click="sendOverview('婚姻')" class="px-3 py-1 bg-pink-400 rounded text-sm">婚</button>
                </div>
              </div>

              <div class="grid grid-cols-3 md:grid-cols-6 gap-3">
                <div v-for="(palace, idx) in palaces" :key="palace.name" @click="showPalaceDetail(idx)"
                  :class="['p-3 rounded cursor-pointer border', activePalace === idx ? 'border-purple-600 bg-purple-50' : 'border-gray-200 bg-white']">
                  <div class="text-sm font-semibold">{{ palace.name }}</div>
                  <div class="text-xs text-gray-600 mt-2">主星：{{ palace.majorStars.map(s=>s.name).join(' ') || '—' }}</div>
                  <div class="text-xs text-gray-400 mt-1">辅星：{{ palace.minorStars.map(s=>s.name).join(' ') || '—' }}</div>
                </div>
              </div>

              <div v-if="activePalace !== null" class="mt-4 border-t pt-4">
                <h3 class="text-lg font-medium">{{ palaces[activePalace].name }} - 宫位详情</h3>
                <div class="mt-2 text-sm text-gray-700 space-y-2">
                  <div>主星：{{ palaces[activePalace].majorStars.map(s=>s.name).join('、') || '无' }}</div>
                  <div>辅星：{{ palaces[activePalace].minorStars.map(s=>s.name).join('、') || '无' }}</div>
                  <div>杂耀：{{ palaces[activePalace].adjectiveStars.map(s=>s.name).join('、') || '无' }}</div>
                  <div v-if="palaces[activePalace].horoscopeMutagens">四化：
                    <span v-if="palaces[activePalace].horoscopeMutagens.禄" class="mr-1">化禄</span>
                    <span v-if="palaces[activePalace].horoscopeMutagens.权" class="mr-1">化权</span>
                    <span v-if="palaces[activePalace].horoscopeMutagens.科" class="mr-1">化科</span>
                    <span v-if="palaces[activePalace].horoscopeMutagens.忌" class="mr-1">化忌</span>
                  </div>
                  <div class="detail-item" v-if="palaces[activePalace].ages && palaces[activePalace].ages.length > 0">
                    <span class="detail-value">小限：{{ palaces[activePalace].ages.join(', ') }}岁 {{ palaces[activePalace].Decadal || '' }}</span>
                  </div>
                  <div class="detail-item" v-if="palaces[activePalace].decadal">
                    <span class="detail-value2">大限：{{ palaces[activePalace].decadal.range[0] }}~{{ palaces[activePalace].decadal.range[1] }}</span>
                  </div>
                </div>

                <div class="mt-4 flex space-x-2">
                  <button @click="analyzePalaceByIndex(activePalace)" class="px-3 py-1 bg-indigo-600 text-white rounded">发送到聊天分析</button>
                  <button @click="activePalace = null" class="px-3 py-1 border rounded">关闭</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
definePageMeta({ middleware: 'admin-access' })
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useZiwei } from '~/composables/useZiwei'

const name = ref('')
const dateType = ref('solar')
const date = ref('')
const timeIndex = ref('0')
const gender = ref('male')
const isLeapMonth = ref(false)

const palaces = ref([])
const fiveElementsClass = ref('')
const majorStar = ref('')
const activePalace = ref(null)

const { loading, generateZiwei } = useZiwei()
const router = useRouter()

const timeOptions = [
  { label: '早子时 (00:00-1:00)', value: '0' },
  { label: '丑时 (1:00-3:00)', value: '1' },
  { label: '寅时 (3:00-5:00)', value: '2' },
  { label: '卯时 (5:00-7:00)', value: '3' },
  { label: '辰时 (7:00-9:00)', value: '4' },
  { label: '巳时 (9:00-11:00)', value: '5' },
  { label: '午时 (11:00-13:00)', value: '6' },
  { label: '未时 (13:00-15:00)', value: '7' },
  { label: '申时 (15:00-17:00)', value: '8' },
  { label: '酉时 (17:00-19:00)', value: '9' },
  { label: '戌时 (19:00-21:00)', value: '10' },
  { label: '亥时 (21:00-23:00)', value: '11' },
  { label: '晚子时 (23:00-00:00)', value: '12' }
]

async function onGenerate() {
  if (!date.value) {
    alert('请选择出生日期')
    return
  }

  try {
    const res = await generateZiwei({ date: date.value, timeIndex: timeIndex.value, gender: gender.value, dateType: dateType.value, isLeapMonth: isLeapMonth.value })
    palaces.value = res.palaces || []
    fiveElementsClass.value = res.fiveElementsClass
    majorStar.value = res.majorStar
    activePalace.value = null
  } catch (err) {
    console.error(err)
    alert('排盘失败：' + (err.message || err))
  }
}

function showPalaceDetail(idx) {
  activePalace.value = idx
}

async function analyzePalaceByIndex(index) {
  if (!palaces.value || !palaces.value[index]) {
    alert('宫位数据不存在')
    return
  }

  const palace = palaces.value[index]
  const birthInfo = dateType.value === 'solar' ? `阳历：${date.value} ${timeOptions[parseInt(timeIndex.value)].label}` : `农历：${date.value}${isLeapMonth.value ? ' 闰' : ''} ${timeOptions[parseInt(timeIndex.value)].label}`
  const desc = `性别：${gender.value === 'male' ? '男' : '女'}\n生辰：${birthInfo}\n宫位：${palace.name}\n主星：${palace.majorStars.map(s=>s.name).join('、') || '无'}\n辅星：${palace.minorStars.map(s=>s.name).join('、') || '无'}\n杂耀：${palace.adjectiveStars.map(s=>s.name).join('、') || '无'}`

  import('@/lin/util/data-transfer').then(({ saveData, generateUniqueId }) => {
    const id = generateUniqueId()
    const success = saveData(id, desc)
    if (success) {
      window.open(`/ai-tools/chat?data_id=${id}`)
    } else {
      alert('保存数据失败')
    }
  }).catch(e => {
    console.error(e)
    alert('无法加载数据传输工具')
  })
}

function sendOverview(type) {
  const birthInfo = dateType.value === 'solar' ? `阳历：${date.value} ${timeOptions[parseInt(timeIndex.value)].label}` : `农历：${date.value}${isLeapMonth.value ? ' 闰' : ''} ${timeOptions[parseInt(timeIndex.value)].label}`
  let infos = `这是我的紫薇排盘生辰信息\n性别：${gender.value === 'male' ? '男' : '女'}\n生辰：${birthInfo}\n`;
  palaces.value.forEach(p => {
    infos += `\n${p.name}：主星 ${p.majorStars.map(s=>s.name).join('、') || '无'}，辅星 ${p.minorStars.map(s=>s.name).join('、') || '无'}`
  })

  import('@/lin/util/data-transfer').then(({ saveData, generateUniqueId }) => {
    const id = generateUniqueId()
    const ok = saveData(id, infos)
    if (ok) window.open(`/ai-tools/chat?data_id=${id}`)
  }).catch(e => {
    console.error(e)
    alert('保存或跳转失败')
  })
}
</script>
